package com.gack.netty.clientTest;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

/**
 * 
* @ClassName: NettyClientConnectionListener 
* @Description: TODO(连接监听类 channel连接时设置该监听  如果连接失败  调用run方法重连) 
* @author (ZhangXinYu)  
* @date 2018年8月31日 上午10:18:15 
* @version V1.0
 */
public class ConnectionListener implements ChannelFutureListener {  
	  private NettyClient client;  
	  public ConnectionListener(NettyClient client) {  
	    this.client = client;  
	  }
	  
	  @Override 
	  public void operationComplete(ChannelFuture channelFuture) throws Exception {
		System.out.println("客户端连接被关闭  尝试重新连接");
	    if (!channelFuture.isSuccess()) { 
	      System.out.println("Reconnect");  
	      final EventLoop loop = channelFuture.channel().eventLoop();  
	      loop.schedule(new Runnable() {  
	        @Override 
	        public void run() {  
	        	try {
					client.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
	        }  
	      }, 1L, TimeUnit.SECONDS);  
	    }  
	  }  
}
